<template>
  <div class="my">
    <Navbar>
      <template #right>
        <div class="title_background__more" @click="handleClickMore">
          <Icon name="sangediandian1" size="18" color="#fff" />
          <div class="EditExit" :class="{ 'active': isEditExitActive }">
            <div class="EditExit__item" @click="showEditPersonalInformation = true">修改个人信息</div>
            <div class="EditExit__item" @click="handleExitLogin">退出登录</div>
          </div>
        </div>
      </template>
    </Navbar>
    <div class="my_title_background" :style="{
      height: backgroundHeight + 'px',
      transform: `scale(${backgroundScale})`,
      '--scale': backgroundScale,
      opacity: backgroundOpacity
    }">
      <img class="background" src="http://43.138.15.137:8080/assets/img/281578538336_.pic_hd.e816ad71.jpg" alt="">
    </div>
    <div class="profile" @touchstart.passive="handleTouchStart" @touchmove.passive="handleTouchMove"
      @touchend.passive="handleTouchEnd" @mousedown="handleMouseDown"
      :style="{ transform: `translate(0px, 0px) scale(1) translateZ(0px)` }">
      <div class="avatar_wrap">
        <img class="avatar" :src="userAvatar" alt="">
      </div>
      <div class="name_wrap">
        <div class="name">
          {{ userNickname }}
        </div>
        <div class="subname">
          抖音号: {{ userId }}
        </div>
      </div>
      <div class="desc_wrap">
        <div class="desc">{{ userDesc }}</div>
        <div class="desc_wrap_info">
          <div class="gender">
            <Icon :name="userGender === '男' ? 'nanxing' : 'women-line'" size="12"
              :color="userGender === '男' ? '#448fe0' : '#ec407a'" />
            <span>{{ userGender === '男' ? '男' : '女' }}</span>
          </div>
          <div class="desc_wrap_info_age">
            <span>{{ userAge }}岁</span>
          </div>
          <!-- 地址 -->
          <div class="desc_wrap_info_address">
            <span>{{ userAddress }}</span>
          </div>
        </div>

      </div>
      <div class="num_wrap">
        <div class="li">获赞{{ likeNum }}</div>
        <div class="li" @click="handleGoMyfollowings">关注{{ followNum }}</div>
        <div class="li" @click="handleGoMyFans">粉丝{{ fanNum }}</div>
      </div>
      <Tab @change="handleTabChange">
        <TabItem :title="`作品${dynamicNum}`">

          <div v-if="tabLoading.work" class="tab-loading">
            <span class="icon">
              <Icon name="jiazailoadding" color="red" size="24" />
            </span>
            <span>加载中...</span>
          </div>
          <div v-else-if="tabTimeout.work || workList.length === 0" class="tab-no-data">
            暂无作品
          </div>
          <div v-else class="tab_list">
            <div class="tab_list_item" v-for="(item, index) in workList" :key="item.videoId"
              @click="handleClickWork(index)">
              <img :src="item.videoCover" alt="" />
              <div class="tab_list_item__delete" @click.stop="handleDeleteWork(item.videoId)">
                <Icon name="icon" size="16" color="#fff" />
              </div>
              <div class="tab_list_item__like">
                <Icon name="xin-2" size="14" color="#ccc" />
                <span>{{ item.likeNum }}</span>
              </div>
            </div>
          </div>
        </TabItem>
        <TabItem :title="`动态${dynamicNum}`">
          <div v-if="tabLoading.dynamic" class="tab-loading">
            <span class="icon">
              <Icon name="jiazailoadding" color="red" size="24" />
            </span>
            <span>加载中...</span>
          </div>
          <div v-else-if="tabTimeout.dynamic || dynamicList.length === 0" class="tab-no-data">
            暂无动态
          </div>
          <div class="follow-page">
            <!-- 动态列表 -->
            <div class="post-item" v-for="(item, index) in dynamicList" :key="item.videoId">
              <!-- 发布者信息 -->
              <div class="post-header">
                <img :src="item.userAvatar" alt="avatar" class="avatar" />
                <span class="username">@{{ item.userNickname }}</span>
              </div>

              <!-- 内容描述 -->
              <div class="post-meta">{{ item.videoDesc }}</div>

              <!-- 媒体内容（视频） -->
              <!-- 视频容器 -->
              <div class="post-media" @click="togglePlay(index)">
                <video ref="videoRefs" class="media-video" :src="item.videoPath" preload="metadata" playsinline
                  webkit-playsinline x5-playsinline loop :muted="false"></video>

                <!-- 播放/暂停覆盖层 -->
                <div v-if="videoStates[index] === 'paused'" class="play-overlay">
                  <Icon name="zantingtubiao" color="#fff" size="32" />
                </div>
              </div>
              <!-- 互动按钮 -->
              <div class="post-actions">
                <div class="action-item" @click="handleDynamicClickLike(item.videoId)">
                  <Icon name="xin-2" :color="item.isLiked ? '#ff4d4f' : '#ccc'" size="20" />
                  <span class="count">{{ item.likeNum }}</span>
                </div>
                <div class="action-item" @click="handleClickComment(item.videoId)">
                  <Icon name="pinglun" color="#fff" size="20"></Icon>
                  <span class="count">{{ item.commentNum }}</span>
                </div>
                <div class="action-item">
                  <Icon name="a-fenxiangweifenxiang" color="#fff" size="18"></Icon>
                  <span class="count">{{ item.shareNum }}</span>
                </div>
              </div>

              <!-- 时间 -->
              <div class="post-time">{{ item.createdAt }}</div>
            </div>
            <!-- 评论弹窗 -->
            <CommentModal v-if="showCommentModal" v-model="showCommentModal" :videoId="videoCommentsVideoId" />
          </div>
        </TabItem>
        <!-- 喜欢 -->
        <TabItem :title="`喜欢${likeVideoNum}`">
          <div v-if="tabLoading.like" class="tab-loading">
            <span class="icon">
              <Icon name="jiazailoadding" color="red" size="24" />
            </span>
            <span>加载中...</span>
          </div>
          <div v-else-if="tabTimeout.like || likeList.length === 0" class="tab-no-data">
            暂无喜欢
          </div>
          <div v-else>
            <div ref="likeContainerRef" class="like-container" @scroll="onLikeScroll">
              <div class="tab_list">
                <div class="tab_list_item" v-for="(item, index) in likeList" :key="item.videoId"
                  @click="handleClickLike(index)">
                  <img :src="item.videoCover" alt="" />
                  <div class="tab_list_item__like">
                    <Icon name="aixin" size="14" color="#fff" />
                    <span>{{ item.likeNum }}</span>
                  </div>
                </div>
              </div>

              <!-- 喜欢列表的分页加载状态（保留你原有的） -->
              <div v-if="loading && likeList.length > 0" class="loading-more">
                <Icon name="jiazailoadding" color="red" size="16" /> 加载中...
              </div>
              <div v-else-if="!hasMore && likeList.length > 0" class="no-more">暂无更多喜欢</div>
            </div>
          </div>
        </TabItem>
      </Tab>
    </div>
    <!-- 视频播放页 -->
    <transition name="fade-left">

      <VerticalFeed v-if="showVerticalFeed" v-model="showVerticalFeed" :currentIndex="currentVideoIndex"
        :feedData="VideoList" />
    </transition>

    <!-- 编辑个人资料 -->
    <transition name="fade-left">
      <EditPersonalInformation v-if="showEditPersonalInformation" v-model="showEditPersonalInformation" />
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, reactive, defineAsyncComponent, watch, defineOptions } from 'vue'
defineOptions({
  name: 'My',
})
import Icon from '@/components/common/Icon.vue'
import Navbar from '@/components/common/Navbar.vue'
import { formatTimeAgo } from '@/utils/time'
// 在任何组件中使用
import { showDialog } from '@/utils/showDialog'
import { Toast } from '@/utils/showtoast'



// 1.用户信息 - 本地存储
import { useUserStore } from '@/stores/userinfo'
const userInfo = useUserStore()
const user = computed(() => userInfo.userInfo)
// 使用计算属性来获取用户信息，确保响应式更新
const userNickname = computed(() => user.value?.userNickname)
const userId = computed(() => user.value?.userId)
const userDesc = computed(() => user.value?.userDesc)
const userAge = computed(() => user.value?.userAge)
const userAddress = computed(() => user.value?.userAddress)
const userGender = computed(() => user.value?.userGender)
const userAvatar = computed(() => user.value?.userAvatar)
// 1.用户信息 


// 2.导入tab tabitem
import Tab from '@/components/common/Tab.vue'
import TabItem from '@/components/common/TabItem.vue'

// 3 导入请求api集合
import { getWorkListAPI, getDynamicListAPI, getDynamicVideoLikeStatusAPI, getLikeListAPI, postVideoLikeAPI, getFollowNumAPI, getFanNumAPI, getLikeNumAPI, getLikeVideoNumAPI, getDynamicNumAPI } from '@/api/my'

// 缓存状态：是否已加载过
const tabLoaded = reactive({
  work: false,      // 作品
  dynamic: false,   // 动态
  like: false       // 喜欢
})

// 加载中状态（用于显示 loading）
const tabLoading = reactive({
  work: false,
  dynamic: false,
  like: false
})

// 超时状态（5秒未加载成功）
const tabTimeout = reactive({
  work: false,
  dynamic: false,
  like: false
})
// 作品列表
const workList = ref([])
const getWorkList = async () => {
  try {
    const res = await getWorkListAPI(userId.value)
    // 
    const mergedList = res.data.map(item => ({
      ...item.Video,
      ...item.WSLCNum
    }))
    // 3. 拼接头像前缀
    mergedList.forEach(item => {
      item.userAvatar = 'http://43.138.15.137:3000' + item.userAvatar
    })
    workList.value = mergedList || []
    console.log(workList.value)
  } catch (error) {
    console.log(error)
  }
}

// 动态列表
const dynamicList = ref([])
const getDynamicList = async () => {
  try {
    // 1. 获取动态列表
    const res = await getDynamicListAPI(userId.value)
    if (!res.data?.length) {
      dynamicList.value = []
      return
    }

    // 2. 合并 Video + WSLCNum + 格式化时间
    let mergedList = res.data.map(item => ({
      ...item.Video,
      ...item.WSLCNum,
      createdAt: formatTimeAgo(item.Video.createdAt)
    }))

    // 3. 拼接头像前缀
    mergedList.forEach(item => {
      item.userAvatar = 'http://43.138.15.137:3000' + item.userAvatar
    })

    // 4. 并发请求每条视频的点赞状态
    const likeStatusPromises = mergedList.map(item =>
      getDynamicVideoLikeStatusAPI(userId.value, item.videoId)
        .then(res => res.data) // 提取 true/false
        .catch(() => false)    // 出错默认为 false
    )

    const likeStatusList = await Promise.all(likeStatusPromises)

    // 5. 合并 isLiked 字段
    mergedList = mergedList.map((item, index) => ({
      ...item,
      isLiked: likeStatusList[index]
    }))

    // 6. 赋值
    dynamicList.value = mergedList
    console.log('获取我的页面动态列表成功:', dynamicList.value)

  } catch (error) {
    console.error('获取动态列表失败:', error)
    dynamicList.value = []
  }
}

// 喜欢列表
const likeList = ref([])
const page = ref(1)
const hasMore = ref(true) // 是否还有更多数据
const loading = ref(false) // 是否正在加载
const getLikeList = async (isLoadMore = false) => {
  if (loading.value || !hasMore.value) return // 防止重复请求

  loading.value = true

  try {
    const res = await getLikeListAPI(userId.value, page.value)

    // 如果是第一页，清空旧数据（可选，通常不需要）
    if (!isLoadMore) {
      likeList.value = []
    }

    if (!res.data?.length) {
      // 当前页无数据 → 没有更多了
      hasMore.value = false
    } else {
      // 合并 Video + WSLCNum
      const mergedList = res.data.map(item => ({
        ...item.Video,
        ...item.WSLCNum,
        userAvatar: 'http://43.138.15.137:3000' + item.Video.userAvatar
      }))
      console.log(mergedList)

      // 拼接到现有列表
      likeList.value = isLoadMore ? [...likeList.value, ...mergedList] : mergedList

      // 如果返回数据少于一页（比如一页10条，只返回5条），也可以认为没更多了
      hasMore.value = res.data.length >= 10 // 可选增强判断
    }
  } catch (error) {
    console.error('获取喜欢列表失败:', error)
    hasMore.value = false
  } finally {
    loading.value = false
  }
}
// 喜欢列表 - 滚动加载更多
const likeContainerRef = ref(null)

const onLikeScroll = () => {
  if (loading.value || !hasMore.value || !likeContainerRef.value) return

  const el = likeContainerRef.value
  if (el.scrollHeight - el.scrollTop <= el.clientHeight + 20) {
    page.value++
    getLikeList(true)
  }
}
// tab发生变化时，更新 activeIndex
const handleTabChange = (index) => {
  // 设置当前 tab 的 loading 为 true（即使已加载，也允许“刷新”？根据需求）
  // 但你要求“同一个不再请求”，所以只在未加载时请求

  switch (index) {
    case 0: // 作品
      if (!tabLoaded.work && !tabLoading.work) {
        loadWorkTab()
      }
      break
    case 1: // 动态
      if (!tabLoaded.dynamic && !tabLoading.dynamic) {
        loadDynamicTab()
      }
      break
    case 2: // 喜欢
      if (!tabLoaded.like && !tabLoading.like) {
        loadLikeTab()
      }
      break
  }
}
const TIMEOUT_DURATION = 5000 // 5秒

const loadWorkTab = async () => {
  tabLoading.work = true
  tabTimeout.work = false

  // 设置 5 秒超时
  const timeoutId = setTimeout(() => {
    tabTimeout.work = true
    tabLoading.work = false
  }, TIMEOUT_DURATION)

  try {
    await getWorkList()
    clearTimeout(timeoutId)
    tabLoaded.work = true
  } catch (error) {
    clearTimeout(timeoutId)
    tabTimeout.work = true
    console.error('作品加载失败:', error)
  } finally {
    tabLoading.work = false
  }
}

const loadDynamicTab = async () => {
  tabLoading.dynamic = true
  tabTimeout.dynamic = false

  const timeoutId = setTimeout(() => {
    tabTimeout.dynamic = true
    tabLoading.dynamic = false
  }, TIMEOUT_DURATION)

  try {
    await getDynamicList()
    clearTimeout(timeoutId)
    tabLoaded.dynamic = true
  } catch (error) {
    clearTimeout(timeoutId)
    tabTimeout.dynamic = true
    console.error('动态加载失败:', error)
  } finally {
    tabLoading.dynamic = false
  }
}

const loadLikeTab = async () => {
  tabLoading.like = true
  tabTimeout.like = false

  const timeoutId = setTimeout(() => {
    tabTimeout.like = true
    tabLoading.like = false
  }, TIMEOUT_DURATION)

  try {
    await getLikeList()
    clearTimeout(timeoutId)
    tabLoaded.like = true
  } catch (error) {
    clearTimeout(timeoutId)
    tabTimeout.like = true
    console.error('喜欢列表加载失败:', error)
  } finally {
    tabLoading.like = false
  }
}

onMounted(async () => {
  // 并行请求所有数据
  try {
    await Promise.all([
      getWorkList(),
      getFanNum(),
      getFollowNum(),
      getLikeNum(),
      getLikeVideoNum(),
      getDynamicNum()
    ]);

    // 数据加载完成后，更新 tabKey 以强制重新渲染 Tab 组件
    tabKey.value += 1;
  } catch (error) {
    console.error('初始化数据加载失败:', error);
  }

  document.addEventListener('click', handleGlobalClick);
})

// 添加清理函数，确保组件卸载时取消动画帧和移除事件监听器
onUnmounted(() => {
  // 取消任何正在进行的动画
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
    animationFrameId = null
  }

  // 移除事件监听器
  document.removeEventListener('click', handleGlobalClick)
  document.removeEventListener('mousemove', handleDocumentMouseMove)
  document.removeEventListener('mouseup', handleDocumentMouseUp)
})



// 视频播放/暂停状态
// 切换播放/暂停
const videoStates = ref({})
const videoRefs = ref([])

const togglePlay = async (index) => {
  const video = videoRefs.value[index]
  if (!video) return

  const currentState = videoStates.value[index] || 'idle'

  if (currentState === 'playing') {
    // 播放 → 暂停
    video.pause()
    videoStates.value[index] = 'paused'
  } else {
    // 暂停 或 idle → 播放
    // 暂停所有其他视频，并重置为 idle（隐藏图标）
    videoRefs.value.forEach((v, i) => {
      if (v && i !== index) {
        v.pause()
        videoStates.value[i] = 'idle'
      }
    })

    try {
      await video.play()
      videoStates.value[index] = 'playing'
    } catch (err) {
      console.warn('播放失败:', err)
      videoStates.value[index] = 'idle'
    }
  }
}
// 删除作品
const handleDeleteWork = (videoId) => {
  // 调用删除接口
  showDialog({
    title: '提示',
    message: '删除后无法恢复，是否继续？',
    onConfirm: () => {
      Toast('暂不支持删除', {
        position: 'bottom'
      })
    },
    onCancel: () => {
      console.log('已取消')
    }
  })
}

// 点击右上角显示退出和修改个人信息弹窗
const isEditExitActive = ref(false)
const handleClickMore = (e) => {
  e.stopPropagation()
  isEditExitActive.value = !isEditExitActive.value
}
// // 全局点击处理
const handleGlobalClick = (e) => {
  // 判断点击的是否是 .EditExit 或其子元素
  const editExitEl = document.querySelector('.EditExit')
  if (editExitEl && !editExitEl.contains(e.target)) {
    closeEditExit()
  }
}
const closeEditExit = () => isEditExitActive.value = false



// // 拖拽相关状态
const backgroundHeight = ref(150) // 初始高度
const backgroundScale = ref(1) // 添加缩放比例变量
const backgroundOpacity = ref(1) // 添加透明度变量
const isDragging = ref(false)
const startY = ref(0)
const currentY = ref(0)
const dragThreshold = 5 // 判断是拖拽还是点击的阈值
const scrollThreshold = 50 // 判断是否在顶部的阈值
let initialScrollTop = 0 // 记录初始滚动位置
let animationFrameId = null // 用于动画帧ID
let lastTimestamp = 0 // 用于计算动画时间差
let velocity = 0 // 用于记录拖拽速度

// // 触摸事件处理
const handleTouchStart = (e) => {
  // 取消任何正在进行的动画
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
    animationFrameId = null
  }

  startY.value = e.touches[0].clientY
  isDragging.value = false
  initialScrollTop = window.pageYOffset || document.documentElement.scrollTop
  lastTimestamp = Date.now()
  velocity = 0
}

const handleTouchMove = (e) => {
  currentY.value = e.touches[0].clientY
  const deltaY = currentY.value - startY.value
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop

  // 计算时间差和速度
  const currentTime = Date.now()
  const timeDiff = currentTime - lastTimestamp
  if (timeDiff > 0) {
    velocity = deltaY / timeDiff
    lastTimestamp = currentTime
  }

  // 判断是否在页面顶部且向下拖拽
  if (currentScrollTop <= scrollThreshold && deltaY > dragThreshold) {
    // 在顶部且向下拖拽，标记为拖拽状态
    isDragging.value = true

    // 使用更自然的阻尼算法
    // 前段使用较小的阻尼，后段使用较大的阻尼
    let dampingFactor
    if (deltaY < 100) {
      // 前段：线性增长，阻尼较小
      dampingFactor = 0.5
    } else {
      // 后段：使用对数增长，阻尼逐渐增大
      dampingFactor = 0.5 + (Math.log(deltaY / 100) * 0.15)
      dampingFactor = Math.min(dampingFactor, 0.85) // 限制最大阻尼
    }

    const adjustedDeltaY = deltaY * dampingFactor
    const newHeight = Math.min(150 + adjustedDeltaY, 350) // 限制最大高度为350px
    backgroundHeight.value = newHeight

    // 计算缩放比例，基于高度变化，使用更平滑的曲线
    const heightRatio = Math.pow((newHeight - 150) / 200, 0.8) // 使用幂函数使变化更平滑
    backgroundScale.value = 1 + heightRatio * 0.25 // 增加缩放比例，确保填充整个区域

    // 添加透明度变化，增加层次感
    backgroundOpacity.value = Math.max(0.85, 1 - (heightRatio * 0.15))
  }
}

const handleTouchEnd = () => {
  if (!isDragging.value) return

  // 使用速度来决定回弹动画的时长和缓动
  const duration = Math.min(600, Math.max(300, Math.abs(velocity) * 50))

  // 使用requestAnimationFrame实现平滑回弹动画
  const startTime = performance.now()
  const startHeight = backgroundHeight.value
  const startScale = backgroundScale.value
  const startOpacity = backgroundOpacity.value

  // 使用自定义缓动函数，模拟弹性回弹
  const easeOutElastic = (t) => {
    const p = 0.3
    return Math.pow(2, -10 * t) * Math.sin((t - p / 4) * (2 * Math.PI) / p) + 1
  }

  const animate = (currentTime) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)

    // 应用缓动函数
    const easedProgress = easeOutElastic(progress)

    // 更新值
    backgroundHeight.value = startHeight + (150 - startHeight) * easedProgress
    backgroundScale.value = startScale + (1 - startScale) * easedProgress
    backgroundOpacity.value = startOpacity + (1 - startOpacity) * easedProgress

    if (progress < 1) {
      animationFrameId = requestAnimationFrame(animate)
    } else {
      // 确保最终值正确
      backgroundHeight.value = 150
      backgroundScale.value = 1
      backgroundOpacity.value = 1
      animationFrameId = null
    }
  }

  animationFrameId = requestAnimationFrame(animate)
  isDragging.value = false
}

// // 鼠标事件处理（用于桌面端）
const handleMouseDown = (e) => {
  // 取消任何正在进行的动画
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
    animationFrameId = null
  }

  startY.value = e.clientY
  isDragging.value = false
  initialScrollTop = window.pageYOffset || document.documentElement.scrollTop
  lastTimestamp = Date.now()
  velocity = 0
  document.addEventListener('mousemove', handleDocumentMouseMove)
  document.addEventListener('mouseup', handleDocumentMouseUp)
}

const handleDocumentMouseMove = (e) => {
  currentY.value = e.clientY
  const deltaY = currentY.value - startY.value
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop

  // 计算时间差和速度
  const currentTime = Date.now()
  const timeDiff = currentTime - lastTimestamp
  if (timeDiff > 0) {
    velocity = deltaY / timeDiff
    lastTimestamp = currentTime
  }

  // 判断是否在页面顶部且向下拖拽
  if (currentScrollTop <= scrollThreshold && deltaY > dragThreshold) {
    isDragging.value = true

    // 使用更自然的阻尼算法
    // 前段使用较小的阻尼，后段使用较大的阻尼
    let dampingFactor
    if (deltaY < 100) {
      // 前段：线性增长，阻尼较小
      dampingFactor = 0.5
    } else {
      // 后段：使用对数增长，阻尼逐渐增大
      dampingFactor = 0.5 + (Math.log(deltaY / 100) * 0.15)
      dampingFactor = Math.min(dampingFactor, 0.85) // 限制最大阻尼
    }

    const adjustedDeltaY = deltaY * dampingFactor
    const newHeight = Math.min(150 + adjustedDeltaY, 350) // 限制最大高度为350px
    backgroundHeight.value = newHeight

    // 计算缩放比例，基于高度变化，使用更平滑的曲线
    const heightRatio = Math.pow((newHeight - 150) / 200, 0.8) // 使用幂函数使变化更平滑
    backgroundScale.value = 1 + heightRatio * 0.25 // 增加缩放比例，确保填充整个区域

    // 添加透明度变化，增加层次感
    backgroundOpacity.value = Math.max(0.85, 1 - (heightRatio * 0.15))

    // 阻止默认行为，防止页面滚动
    if (e.target.closest('.profile')) {
      e.preventDefault()
    }
  }
}

const handleDocumentMouseUp = () => {
  document.removeEventListener('mousemove', handleDocumentMouseMove)
  document.removeEventListener('mouseup', handleDocumentMouseUp)

  if (!isDragging.value) return

  // 使用速度来决定回弹动画的时长和缓动
  const duration = Math.min(600, Math.max(300, Math.abs(velocity) * 50))

  // 使用requestAnimationFrame实现平滑回弹动画
  const startTime = performance.now()
  const startHeight = backgroundHeight.value
  const startScale = backgroundScale.value
  const startOpacity = backgroundOpacity.value

  // 使用自定义缓动函数，模拟弹性回弹
  const easeOutElastic = (t) => {
    const p = 0.3
    return Math.pow(2, -10 * t) * Math.sin((t - p / 4) * (2 * Math.PI) / p) + 1
  }

  const animate = (currentTime) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)

    // 应用缓动函数
    const easedProgress = easeOutElastic(progress)

    // 更新值
    backgroundHeight.value = startHeight + (150 - startHeight) * easedProgress
    backgroundScale.value = startScale + (1 - startScale) * easedProgress
    backgroundOpacity.value = startOpacity + (1 - startOpacity) * easedProgress

    if (progress < 1) {
      animationFrameId = requestAnimationFrame(animate)
    } else {
      // 确保最终值正确
      backgroundHeight.value = 150
      backgroundScale.value = 1
      backgroundOpacity.value = 1
      animationFrameId = null
    }
  }

  animationFrameId = requestAnimationFrame(animate)
  isDragging.value = false
}

// 视频播放组件
const showVerticalFeed = ref(false)
const VerticalFeed = defineAsyncComponent(() => import('@/components/common/VerticalFeed.vue'))
// 视频播放页 - 作品
const VideoList = ref([])
const currentVideoIndex = ref(0)
const handleClickWork = (index) => {
  showVerticalFeed.value = true
  currentVideoIndex.value = index
  VideoList.value = workList.value
  console.log(VideoList.value)
}
// 视频播放页 - 喜欢
const handleClickLike = (index) => {
  showVerticalFeed.value = true
  currentVideoIndex.value = index
  VideoList.value = likeList.value
  console.log(VideoList.value)
}

// 动态 - 评论弹窗
const CommentModal = defineAsyncComponent(() => import('@/components/common/CommentModal.vue'))
const showCommentModal = ref(false)
const videoCommentsVideoId = ref('')
const handleClickComment = (videoId) => {
  videoCommentsVideoId.value = videoId
  showCommentModal.value = true
}

// 动态 - 点赞
const handleDynamicClickLike = async (videoId) => {
  try {
    const res = await postVideoLikeAPI(userId.value, videoId)
    if (res.code === 200) {
      // 刷新动态点赞状态
      const dynamicItem = dynamicList.value.find(item => item.videoId === videoId)
      if (dynamicItem) {
        dynamicItem.isLiked = !dynamicItem.isLiked
      }
      // 更新点赞数量 更新UI 数据返回并没有数量
      if (dynamicItem.isLiked) {
        dynamicItem.likeNum++
      } else {
        dynamicItem.likeNum--
      }
    }
  } catch (error) {
    console.error('点赞失败:', error)
  }
}


// 关注数量
const followNum = ref(0)
const getFollowNum = async () => {
  try {
    const res = await getFollowNumAPI(userId.value)
    if (res.code === 200) {
      followNum.value = res.data
    }
  } catch (error) {
    console.error('关注数量获取失败:', error)
  }
}
// 粉丝数量
const fanNum = ref(0)
const getFanNum = async () => {
  try {
    const res = await getFanNumAPI(userId.value)
    if (res.code === 200) {
      fanNum.value = res.data
    }
  } catch (error) {
    console.error('粉丝数量获取失败:', error)
  }
}
// 获赞数量
const likeNum = ref(0)
const getLikeNum = async () => {
  try {
    const res = await getLikeNumAPI(userId.value)
    if (res.code === 200) {
      likeNum.value = res.data
    }
  } catch (error) {
    console.error('获赞数量获取失败:', error)
  }
}
// 喜欢数量
const likeVideoNum = ref(0)
const getLikeVideoNum = async () => {
  try {
    const res = await getLikeVideoNumAPI(userId.value)
    if (res.code === 200) {
      likeVideoNum.value = res.data
    }
  } catch (error) {
    console.error('喜欢数量获取失败:', error)
  }
}
// 动态数量
const dynamicNum = ref(0)
const getDynamicNum = async () => {
  try {
    const res = await getDynamicNumAPI(userId.value)
    if (res.code === 200) {
      dynamicNum.value = res.data
      console.log(dynamicNum.value)
    }
  } catch (error) {
    console.error('动态数量获取失败:', error)
  }
}



// 个人资料编辑弹窗
const showEditPersonalInformation = ref(false)
const EditPersonalInformation = defineAsyncComponent(() => import('@/views/my/EditPersonalInformation.vue'))


// 跳转我的关注页面
import { useRouter } from 'vue-router'
const router = useRouter()
const handleGoMyfollowings = () => {
  router.push({
    name: 'MyFollowings',
  })
}
// 跳转我的粉丝页面
const handleGoMyFans = () => {
  router.push({
    name: 'MyFans',
  })
}


// 退出登录
const handleExitLogin = () => {
  userInfo.clearUserInfo()
  router.push('/')
  Toast('退出登录成功', {
    position: 'bottom'
  })
}
</script>

<style lang="scss" scoped>
.my {
  position: relative;
  overflow: hidden;
  /* 防止内容溢出影响其他元素 */
  isolation: isolate;
  /* 创建新的层叠上下文，防止影响其他固定定位元素 */
  /* 确保背景图片缩放时不会出现缝隙 */
  background-color: #161622;
  /* 添加背景色，防止缩放时露出底层 */

  // 定位右上角
  .title_background__more {
    width: 32px;
    height: 32px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .EditExit {
      position: absolute;
      top: 100px;
      right: 0;
      width: 80px;
      height: 80px;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 2px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: #fff;
      z-index: 222;
      opacity: 0;
      visibility: hidden;
      transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);

      &.active {
        top: 40px;
        opacity: 1;
        visibility: visible;

      }

      &::after {
        display: block;
        position: absolute;
        top: -15px;
        right: 8px;
        border: 8px solid transparent;
        border-bottom: 8px solid rgba(0, 0, 0, 0.5);
        content: '';
      }

      .EditExit__item {
        flex: 1;
        -webkit-box-flex: 1;
        height: 44px;
        line-height: 44px;
        height: 44px;
        width: 100%;
        text-align: center;
      }

    }
  }
}

.my_title_background {
  width: 100%;
  height: 150px;
  /* 默认高度，会被动态样式覆盖 */
  position: relative;
  overflow: hidden;
  transition: opacity 0.1s ease-out;
  /* 只对透明度应用过渡，其他属性由JS控制 */
  transform-origin: center top;
  z-index: 1;
  /* 确保背景在正确的层级，不影响其他元素 */
  will-change: transform, opacity;
  /* 提示浏览器优化这些属性 */
  /* 确保背景始终填满容器，不出现缝隙 */
  backface-visibility: hidden;
  /* 防止缩放时出现闪烁 */
  /* 确保背景图片缩放时不会出现缝隙 */
  margin-bottom: -1px;
  /* 消除与下方内容的间隙 */


  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.1s ease-out;
    /* 对图片应用轻微过渡效果 */
    /* 确保图片在缩放时不会出现缝隙 */
    transform-origin: center center;
    backface-visibility: hidden;
    /* 确保图片始终填充容器，不留空白 */
    min-width: 100%;
    min-height: 100%;
  }
}

.profile {
  position: relative;
  width: 100%;
  background: #161622;
  transition-timing-function:
    cubic-bezier(0.165, 0.84, 0.44, 1);
  transition-duration: 0ms;
  transform: translate(0px, 0px) scale(1) translateZ(0px);
  z-index: 2;
  /* 确保内容在背景之上 */
  isolation: isolate;
  /* 创建新的层叠上下文，防止影响其他元素 */

  .avatar_wrap {
    position: absolute;
    left: 10px;
    top: -15px;
    border-radius: 50%;
    padding: 5px;
    width: 80px;
    height: 80px;
    background: #161622;

    img {
      border-radius: 50%;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .name_wrap {
    position: relative;
    margin: 0 10px;
    padding: 80px 10px 10px;
    border-bottom: 1px solid rgba(41, 40, 37, 0.8);

    .name {
      color: #fff;
      font-size: 18px;
    }

    .subname {
      margin-top: 5px;
      color: #fff;
      font-size: 12px;
    }
  }

  .desc_wrap {
    margin: 10px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    gap: 15px;

    .desc_wrap_info {
      display: flex;
      gap: 5px;
      align-items: center;

      .gender {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 2px 8px;
        border-radius: 5px;
        background: rgba(67, 51, 63, 0.7);
        font-size: 10px;
        max-width: 50px;
        color: #8b8c96;
        white-space: nowrap;
      }

      .desc_wrap_info_age {
        font-size: 12px;
        color: #8b8c96;

      }

      .desc_wrap_info_address {
        font-size: 12px;
        color: #8b8c96;
      }


    }

    .desc {
      color: #8b8c96;
      font-size: 12px;
    }


  }

  .num_wrap {
    margin: 10px;
    width: 200px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    color: #fff;

    .li {
      font-size: 14px;
    }
  }

  .tab_list {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 46px;

    .tab_list_item {
      position: relative;
      width: 33.33%;
      height: 160px;
      border: 1px solid #000;


      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .tab_list_item__delete {
        position: absolute;
        top: 0;
        right: 2px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .tab_list_item__like {
        position: absolute;
        bottom: 2px;
        left: 6px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: #fff;
        gap: 2px;
      }
    }
  }

  .commit_list_wrap_more {
    text-align: center;
    font-size: 12px;
    color: #65676e;
    margin: 14px 0;
  }

  .follow {
    background-color: #161622;
    padding-bottom: 48px;

    .follow_item {
      width: 98%;
      margin: 10px auto 0;
      display: flex;
      flex-direction: column;
      gap: 10px;
      border-bottom: 1px solid #252425;
      padding: 5px;

      .follow_item_top {
        display: flex;
        align-items: center;
        gap: 5px;

        .follow_item_top__avatar {
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }

        .follow_item_top__username {
          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_desc {
        font-size: 14px;
        color: #fff;
      }

      .follow_item_video {
        width: 250px;
        height: 350px;
      }

      .follow_item_bar {
        display: flex;
        gap: 10px;

        .follow_item_bar_item {
          display: flex;
          align-items: center;
          gap: 5px;

          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_time {
        font-size: 12px;
        color: #fff;
      }
    }
  }
}

// 从左到右过渡出现
.fade-in-right-enter-active,
.fade-in-right-leave-active {
  transition: all 0.3s ease-in-out;
}

.fade-in-right-enter-from,
.fade-in-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

.follow-page {
  background-color: $secondary-color;
  color: white;
  min-height: 100vh;
  margin-bottom: $spacing-xl;

  .post-item {
    background-color: $bg-color;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: $spacing-lg;

    .post-header {
      @include flex-center;
      gap: 8px;
      margin-bottom: 8px;
      justify-content: start;

      .avatar {
        width: 35px;
        height: 35px;
        border-radius: 50%;
      }

      .username {
        font-size: $font-size-base;
        font-weight: 500;
      }
    }

    .post-meta {
      font-size: $font-size-base;
      color: $comment-modal-border-color;
      margin-bottom: $spacing-md;
    }

    .post-media {
      position: relative;

      overflow: hidden;
      width: 80%;
      height: 400px;
      border-radius: $border-radius-md;
      background-color: $black-color;

      .play-overlay {
        width: 100%;
        height: 100%;
        @include absolute-top-right;
        @include flex-center;
      }

      .media-video {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .post-actions {
      width: 80%;
      @include flex-around;
      margin: $spacing-md 0;
      gap: $spacing-lg;

      .action-item {
        @include flex-center;
        color: $comment-modal-border-color;
        font-size: $font-size-small;
        gap: 5px;
      }
    }
  }
}






.like-container {
  height: calc(100vh - 200px); // 根据你的布局调整
  padding-bottom: 46px;
  overflow-y: auto;
}

.loading-more,
.no-more,
.no-data {
  text-align: center;
  padding: 12px;
  color: #999;
  font-size: 14px;
}




.icon-heart {
  color: #ff4d4d;
}

.post-time {
  font-size: $font-size-small;
  color: #999;
  margin-top: $spacing-md;
}

/* 评论区 */
.comment-section {
  margin-top: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-username {
  font-size: 14px;
  font-weight: 500;
}

.tab-loading,
.tab-no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
  font-size: 14px;
}

.tab-loading .icon {
  margin-bottom: 8px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>